/**
 * 
 */
package com.orange.controller.manage;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.orange.controller.BaseController;
import com.orange.dbhelp.page.Page;
import com.orange.handler.manage.AuthSysDownloadService;
import com.orange.modules.entity.manage.AuthSysDownload;
import com.orange.util.AppConfig;
import com.orange.util.ReturnCode;

/**
 * @author gaogs
 *
 * 2016-12-12
 */
@Controller
@RequestMapping("/authSysDownload")
public class AuthSysDownloadController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(AuthSysDownloadController.class);
	
	@Autowired
	private AuthSysDownloadService authSysDownloadService;
	
	@Autowired
	private AppConfig appconfig;
	/**
	 * 0:评估公告  1：下载中心  2：政策法规    保存
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/saveAuthSysDownloadInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveAuthSysDownloadInfo(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
		
		try{
			String type=map.get("type");
			String fileUrl=map.get("fileUrl");
			if(StringUtils.isBlank(type)||StringUtils.isBlank(fileUrl)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "类型或者文件路径为空");
			}
			String name=fileUrl.substring(fileUrl.lastIndexOf("/")+1, fileUrl.length());
			AuthSysDownload asd=new AuthSysDownload();
			asd.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			asd.setFileName(name);
			asd.setFileUrl(fileUrl);
			asd.setType(type);
			authSysDownloadService.saveAuthSysDownloadInfo(asd);
			return toResponse(null, ReturnCode.SUCCESS, "保存成功");
		}catch(Exception e){
			logger.info("保存失败", e);
			return toResponse(null,ReturnCode.FAIL,"保存失败");
		}
	}
	
	
	
	/**
	 * 0:评估公告  1：下载中心  2：政策法规    删除
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/deleteAuthSysDownloadInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> deleteAuthSysDownloadInfo(HttpServletRequest request,@RequestParam String pid) throws SQLException{
		
		try{
			if(StringUtils.isBlank(pid)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "pid为空");
			}
			AuthSysDownload a=authSysDownloadService.queryAuthSysDownloadById(pid);
			if(null==a){
				return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "删除信息不存在");
			}
			authSysDownloadService.deleteAuthSysDownloadInfo(pid);
			return toResponse(null, ReturnCode.SUCCESS, "删除成功");
		}catch(Exception e){
			logger.info("删除失败", e);
			return toResponse(null,ReturnCode.FAIL,"删除失败");
		}
	}
	
	/**
	 * 0:评估公告  1：下载中心  2：政策法规    分页查询
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthSysDownloadInfoPage" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> queryAuthSysDownloadInfoPage(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
		
		try{
			String type=map.get("type");
			String pageSize=map.get("pageSize");
			String pageNumber=map.get("pageNumber");
			if(StringUtils.isBlank(pageSize)||StringUtils.isBlank(pageNumber)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数不可为空");
			}
			Page<AuthSysDownload> page=authSysDownloadService.queryAuthSysDownloadInfoPage(map);
			return toResponse(page, ReturnCode.SUCCESS, "分页查询成功");
		}catch(Exception e){
			logger.info("分页查询失败", e);
			return toResponse(null,ReturnCode.FAIL,"分页查询失败");
		}
	}
	
	/**
	 * 下载文档
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/downloadFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public void downloadFile(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid){
		
		try {
			AuthSysDownload a=authSysDownloadService.queryAuthSysDownloadById(pid);
			if(null==a){
				return;
			}
			//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
			 String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= a.getFileUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        ServletOutputStream out;  
	        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
	        File file = new File(path +filepath);  
	  
	            FileInputStream inputStream = new FileInputStream(file);  
	  
	            //3.通过response获取ServletOutputStream对象(out)  
	            out = response.getOutputStream();  
	            
	            int b = 0;  
	            byte[] buffer = new byte[512];  
	            int count = 0;
		         while ((count = inputStream.read(buffer)) > 0) {
		        	 out.write(buffer, 0, count);
		         }
	            inputStream.close();  
	            out.close();  
	            out.flush();  
	  
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}



	
}
